package com.service.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.service.sms.config.AliyunSmsConfig;
import com.service.sms.service.SmsService;
import com.service.sms.utils.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AliyunSmsConfig aliyunSmsConfig;

    @Override
    public Boolean sendSms(String phone) {
        try {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunSmsConfig.getAccessKeyId(), aliyunSmsConfig.getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", aliyunSmsConfig.getSignName());
            request.putQueryParameter("TemplateCode", aliyunSmsConfig.getTemplateCode());
            Map<String, Object> map = new HashMap<>();
            String code = NumberUtils.generateCode(6);
            map.put("code", code);
            request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

            CommonResponse response = client.getCommonResponse(request);
            ValueOperations<String, String> string = redisTemplate.opsForValue();
            //设置5分钟后过期
            string.set("guli:register:"+phone, code, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
